package com.foreknow.demo11;

import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;

/**
 * 集合（容器）
 * Collection接口用来存放一组称为元素的对象，一个Collection中可以放不同类型
 * 的数据
 */
public class CollectionDemo {
    public void m1(List<Student> students){
        for (Student student:students){
            System.out.println(student.getId());
        }
    }

    public List<Student> m2(List<Student> students){
        return students;
    }
    public static void main(String[] args) {
        Student stu = new Student();
        stu.setId("1001");
        stu.setName("tom");
        stu.setAge(20);
        Student stu1 = new Student();
        stu1.setId("1002");
        stu1.setName("tom2");
        stu1.setAge(30);
        //创建一个集合容器
        //可以使用泛型<E>来约束集合中的元素的类型
        List<Student> list = new ArrayList<Student>();
        //向集合中添加元素，注意：集合中只能存对象(Object)
        list.add(stu);
        list.add(stu1);
        //从集合中获取元素(Student对象)
        Student s = (Student) list.get(0);
        System.out.println(s.getId());
        Student s1 = (Student) list.get(1);
        System.out.println(s1.getId());
        System.out.println("----------");
        //遍历集合
        for(int i = 0;i<list.size();i++) {
            Student st = list.get(i);
            System.out.println(st.getId());
        }
        System.out.println("-----------------");
        //foreach
        for(Student ss:list){
            System.out.println(ss.getId());
        }
        System.out.println("-----------迭代器(Iterator)-------------");
        //迭代器（Iterator）
        Iterator<Student> iterator = list.iterator();
        while(iterator.hasNext()){
            Student student = iterator.next();
            System.out.println(student.getName());
        }


/*        System.out.println("------------------------");
        CollectionDemo collectionDemo = new CollectionDemo();
        collectionDemo.m1(list);
        System.out.println("------------------------");
        List<Student> newList = collectionDemo.m2(list);

        list.remove(1);
        for (Student sss:newList){
            System.out.println(sss.getName());
        }*/
    }
}
